package com.itlong.cloud.intercept.jd;

import com.itlong.cloud.POJO.VO.jd.JDResultVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.jd.JDCodEnum;
import com.itlong.cloud.intercept.sdkV1.CloudTalkSDKServerLoginIntercept;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 * 云设备 入参处理拦截器
 * </desc>
 *
 * @createDate 2019/09/16
 */
@Aspect
@Component
public class SDKJdParamIntercept {
    private static Logger LOG = LoggerFactory.getLogger(CloudTalkSDKServerLoginIntercept.class);

    @Value("${" + PlatformConstants.JD_SECRET + "}")
    private String appSecret;

    // 定义一个切入点
    @Pointcut("(execution(* com.itlong.cloud.controller.jd.elevator.*.*(..)))")
    public void excudeService() {
    }

    /**
     * <desc>
     *      验签拦截器
     * </desc>
     *
     * @param thisJoinPoint
     * @return
     * @author Qiang.S
     * @createDate 2019/09/16
     */
    @Around("excudeService()")
    public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String jsonStr = getRequestPostStr(request);
        if (StringUtils.isBlank(jsonStr)) {
            return new JDResultVO(JDCodEnum.REQUIRED_PARAMETER_IS_EMPTY.getCode());
        }
        Map<String,Object> params = JsonUtil.toObject(jsonStr,HashMap.class);
        LOG.info("【拦截器中参数】" + (params == null ? null : params.toString()));
        String url = request.getServletPath();
        String id = params.get("id").toString();
        if(!DesEncryptUtil.checkJdSign(params,appSecret,url)){
            return new JDResultVO(id,JDCodEnum.REQUEST_SIGNATURE_ERROR.getCode());
        }
        ((HashMap)params.get("params")).put("id",id);
        //封装入参
        request.setAttribute("jsonStr",JsonUtil.toJSON(params.get("params")));
        return thisJoinPoint.proceed();
    }

    /**
     * 描述:获取 post 请求的 byte[] 数组
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws java.io.IOException
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if(contentLength<0){
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength;) {

            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }

    /**
     * 描述:获取 post 请求内容
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }
}